C++ Getting Started
To start using C++, you need two things: A text editor, like Notepad, to write C++ code A compiler, like GCC, to translate the C++ code into a language that the computer will understand There are many text editors and compilers to choose from. In this tutorial, we will use an IDE (see below).
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
C++ Output (Print Text)
The cout object, together with the << operator, is used to output values/print text:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
C++ New Lines
To insert a new line, you can use the \n character:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World! \n";
cout << "Hello World!" << endl;
return 0;
}
C++ Single-line Comments
Comments can be used to explain C++ code, and to make it more readable. It can also be used to prevent execution when testing alternative code. Comments can be singled-lined or multi-lined.
// This is a comment
cout << "Hello World!";
C++ Multi-line Comments
Multi-line comments start with /* and ends with */. Any text between /* and */ will be ignored by the compiler:
#include <iostream>
using namespace std;
int main() {
/* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";
return 0;
}
C++ Variables
Variables are containers for storing data values.
In C++, there are different types of variables (defined with different keywords), for example:
int - stores integers (whole numbers), without decimals, such as 123 or -123
double - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
string - stores text, such as "Hello World". String values are surrounded by double quotes
bool - stores values with two states: true or false
#include <iostream>
using namespace std;
int main() {
int myNum = 15;
cout << myNum;
return 0;
}
Display Variables
The cout object is used together with the << operator to display variables. To combine both text and a variable, separate them with the << operator:
#include <iostream>
using namespace std;
int main() {
int myAge = 35;
cout << "I am " << myAge << " years old.";
return 0;
}
C++ User Input
You have already learned that cout is used to output (print) values. Now we will use cin to get user input. cin is a predefined variable that reads data from the keyboard with the extraction operator (>>). In the following example, the user can input a number, which is stored in the variable x. Then we print the value of x:
#include <iostream>
using namespace std;
int main() {
int x;
cout << "Type a number: "; // Type a number and press enter
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x;
return 0;
}
C++ Basic Data Types
As explained in the Variables chapter, a variable in C++ must be a specified data type:
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
double myDoubleNum = 9.98; // Floating point number
char myLetter = 'D'; // Character
bool myBoolean = true; // Boolean
string myText = "Hello"; // String
C++ Arithmetic Operators
Operators are used to perform operations on variables and values.
#include <iostream>
using namespace std;
int main() {
int x = 100 + 50;
cout << x;
return 0;
}
#include <iostream>
using namespace std;
int main() {
int x = 5;
int y = 3;
cout << x + y;
cout << x - y;
cout << x * y;
cout << x / y;
cout << x % y;
++x;
cout << x;
--x;
cout << x;
return 0;
}
C++ Assignment Operators
Assignment operators are used to assign values to variables. In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:
#include <iostream>
using namespace std;
int main() {
int x = 10;
cout << x;
x += 5;
cout << x;
x -= 3;
cout << x;
x *= 3;
cout << x;
x /= 3;
cout << x;
x %= 3;
cout << x;
x &= 3;
cout << x;
x |= 3;
cout << x;
x ^= 3;
cout << x;
x >>= 3;
cout << x;
x <<= 3;
cout << x;
return 0;
}
C++ Logical Operators
As with comparison operators, you can also test for true (1) or false (0) values with logical operators. Logical operators are used to determine the logic between variables or values:
#include <iostream>
using namespace std;
int main() {
int x = 5;
int y = 3;
cout << (x > 3 && x < 10); // returns true (1) because 5 is greater than 3 AND 5 is less than 10
cout << (x > 3 || x < 4); // returns true (1) because one of the conditions are true (5 is greater than 3, but 5 is not less than 4)
cout << (!(x > 3 && x < 10)); // returns false (0) because ! (not) is used to reverse the result
return 0;
}
C++ Strings
Strings are used for storing text. A string variable contains a collection of characters surrounded by double quotes:
#include <iostream>
#include <string>
using namespace std;
int main() {
string greeting = "Hello";
cout << greeting;
return 0;
}
C++ String Concatenation
The + operator can be used between strings to add them together to make a new string. This is called concatenation:
#include <iostream>
#include <string>
using namespace std;
int main () {
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
cout << fullName;
return 0;
}
C++ String Length
To get the length of a string, use the length() function:
#include <iostream>
#include <string>
using namespace std;
int main() {
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.length();
return 0;
}
C++ Access Strings
You can access the characters in a string by referring to its index number inside square brackets []. This example prints the first character in myString:
#include <iostream>
#include <string>
using namespace std;
int main() {
string myString = "Hello";
cout << myString[0];
return 0;
}
C++ User Input Strings
It is possible to use the extraction operator >> on cin to store a string entered by a user:
string firstName;
cout << "Type your first name: ";
cin >> firstName; // get user input from the keyboard
cout << "Your name is: " << firstName;
// Type your first name: John
// Your name is: John
#include <iostream>
#include <string>
using namespace std;
int main() {
string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;
// Type your full name: John Doe
// Your name is: John Doe
return 0;
}
C++ Math | Max and min
C++ has many functions that allows you to perform mathematical tasks on numbers. The max(x,y) function can be used to find the highest value of x and y:
#include <iostream>
using namespace std;
int main() {
cout << max(5, 10);
return 0;
}
#include <iostream>
using namespace std;
int main() {
cout << min(5, 10);
return 0;
}
C++ <cmath> Header
Other functions, such as sqrt (square root), round (rounds a number) and log (natural logarithm), can be found in the <cmath> header file:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
cout << sqrt(64) << "\n";
cout << round(2.6) << "\n";
cout << log(2) << "\n";
return 0;
}
C++ Booleans
Very often, in programming, you will need a data type that can only have one of two values,
like:
YES / NO
ON / OFF
TRUE / FALSE
For this, C++ has a bool data type, which can take the values true (1) or false (0).
#include <iostream>
using namespace std;
int main() {
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)
return 0;
}
C++ Boolean Expressions
A Boolean expression returns a boolean value that is either 1 (true) or 0 (false).
#include <iostream>
using namespace std;
int main() {
int x = 10;
int y = 9;
cout << (x > y); // returns 1 (true), because 10 is higher than 9
return 0;
}
#include <iostream>
using namespace std;
int main() {
cout << (10 > 9); // returns 1 (true), because 10 is higher than 9
return 0;
}
#include <iostream>
using namespace std;
int main() {
int x = 10;
cout << (x == 10); // returns 1 (true), because the value of x is equal to 10
return 0;
}
C++ Conditions and If Statements
You already know that C++ supports the usual logical conditions from mathematics:
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b
You can use these conditions to perform different actions for different decisions.
C++ has the following conditional statements:
Use if to specify a block of code to be executed, if a specified condition is true
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
Use switch to specify many alternative blocks of code to be executed
if (condition) {
// block of code to be executed if the condition is true
}
C++ Else
Use the else statement to specify a block of code to be executed if the condition is false.
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
C++ Else If
Use the else if statement to specify a new condition if the first condition is false.
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Short Hand If...Else (Ternary Operator)
There is also a short-hand if else, which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line. It is often used to replace simple if else statements:
// variable = (condition) ? expressionTrue : expressionFalse;
#include <iostream>
#include <string>
using namespace std;
int main() {
int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
cout << result; // Output: Good evening.
return 0;
}
C++ Switch Statements
Use the switch statement to select one of many code blocks to be executed.
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
#include <iostream>
using namespace std;
int main() {
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
// Outputs "Thursday" (day 4)
return 0;
}
C++ While Loop
The while loop loops through a block of code as long as a specified condition is true:
while (condition) {
// code block to be executed
}
#include <iostream>
using namespace std;
int main() {
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
return 0;
}
C++ Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
do {
// code block to be executed
}
while (condition);
C++ For Loop
When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
for (int i = 0; i < 5; i++) {
cout << i << "\n";
}
C++ Break and Continue
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a switch statement. The break statement can also be used to jump out of a loop.
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
cout << i << "\n";
}
return 0;
}
/* output :
0
1
2
3
*/
C++ Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
cout << i << "\n";
}
return 0;
}
/* output :
0
1
2
3
5
6
7
8
9
*/
C++ Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. To declare an array, define the variable type, specify the name of the array followed by square brackets and specify the number of elements it should store:
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
Access the Elements of an Array
You access an array element by referring to the index number inside square brackets []. This statement accesses the value of the first element in cars:
#include <iostream>
#include <string>
using namespace std;
int main() {
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
return 0;
}
// Outputs Volvo
Change an Array Element
To change the value of a specific element, refer to the index number:
cars[0] = "Opel";
#include <iostream>
#include <string>
using namespace std;
int main() {
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
cout << cars[0];
return 0;
}
// Now outputs Opel instead of Volvo
C++ Arrays and Loops
You can loop through the array elements with the for loop. The following example outputs all elements in the cars array:
#include <iostream>
#include <string>
using namespace std;
int main() {
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
for (int i = 0; i < 5; i++) {
cout << cars[i] << "\n";
}
return 0;
}
output:
Volvo
BMW
Ford
Mazda
Tesla
#include <iostream>
#include <string>
using namespace std;
int main() {
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
for (int i = 0; i < 5; i++) {
cout << i << " = " << cars[i] << "\n";
}
return 0;
}
Output :
0 = Volvo
1 = BMW
2 = Ford
3 = Mazda
4 = Tesla
#include <iostream>
using namespace std;
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
cout << myNumbers[i] << "\n";
}
return 0;
}
output :
10
20
30
40
50
The foreach Loop
There is also a "for-each loop" (introduced in C++ version 11 (2011)), which is used exclusively to loop through elements in an array:
for (type variableName : arrayName) {
// code block to be executed
}
#include <iostream>
using namespace std;
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i : myNumbers) {
cout << i << "\n";
}
return 0;
}
C++ Omit Array Size
In C++, you don't have to specify the size of the array. The compiler is smart enough to determine the size of the array based on the number of inserted values:
string cars[] = {"Volvo", "BMW", "Ford"}; // Three array elements
string cars[3] = {"Volvo", "BMW", "Ford"}; // Also three array elements
Get the Size of an Array
To get the size of an array, you can use the sizeof() operator:
Why did the result show 20 instead of 5, when the array contains 5 elements?
It is because the sizeof() operator returns the size of a type in bytes.
You learned from the Data Types chapter that an int type is usually 4 bytes, so from the example above,
4 x 5 (4 bytes x 5 elements) = 20 bytes.
#include <iostream>
using namespace std;
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
cout << sizeof(myNumbers);
return 0;
}
output : 20
To find out how many elements an array has, you have to divide the size of the array by the size of the data type it contains:
#include <iostream>
using namespace std;
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
int getArrayLength = sizeof(myNumbers) / sizeof(int);
cout << getArrayLength;
return 0;
}
output : 5
C++ Multi-Dimensional Arrays
A multi-dimensional array is an array of arrays. To declare a multi-dimensional array, define the variable type, specify the name of the array followed by square brackets which specify how many elements the main array has, followed by another set of square brackets which indicates how many elements the sub-arrays have:
string letters[2][4];
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
string letters[2][2][2] = {
{
{ "A", "B" },
{ "C", "D" }
},
{
{ "E", "F" },
{ "G", "H" }
}
};
Access the Elements of a Multi-Dimensional Array
To access an element of a multi-dimensional array, specify an index number in each of the array's dimensions. This statement accesses the value of the element in the first row (0) and third column (2) of the letters array.
#include <iostream>
using namespace std;
int main() {
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
cout << letters[0][2];
return 0;
}
output : C
Change Elements in a Multi-Dimensional Array
To change the value of an element, refer to the index number of the element in each of the dimensions:
#include <iostream>
using namespace std;
int main() {
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
letters[0][0] = "Z";
cout << letters[0][0];
return 0;
}
Now outputs "Z" instead of "A"
Loop Through a Multi-Dimensional Array
To loop through a multi-dimensional array, you need one loop for each of the array's dimensions. The following example outputs all elements in the letters array:
#include <iostream>
using namespace std;
int main() {
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
cout << letters[i][j] << "\n";
}
}
return 0;
}
output :
A
B
C
D
E
F
G
H
C++ Structures (struct)
Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. Unlike an array, a structure can contain many different data types (int, string, bool, etc.).
struct { // Structure declaration
int myNum; // Member (int variable)
string myString; // Member (string variable)
} myStructure; // Structure variable
Access Structure Members
To access members of a structure, use the dot syntax (.):
#include <iostream>
#include <string>
using namespace std;
int main() {
struct {
int myNum;
string myString;
} myStructure;
myStructure.myNum = 1;
myStructure.myString = "Hello World!";
cout << myStructure.myNum << "\n";
cout << myStructure.myString << "\n";
return 0;
}
output :
1
Hello World!
One Structure in Multiple Variables
You can use a comma (,) to use one structure in many variables:
struct {
int myNum;
string myString;
} myStruct1, myStruct2, myStruct3; // Multiple structure variables separated with commas
#include <iostream>
#include <string>
using namespace std;
int main() {
struct {
string brand;
string model;
int year;
} myCar1, myCar2; // We can add variables by separating them with a comma here
// Put data into the first structure
myCar1.brand = "BMW";
myCar1.model = "X5";
myCar1.year = 1999;
// Put data into the second structure
myCar2.brand = "Ford";
myCar2.model = "Mustang";
myCar2.year = 1969;
// Print the structure members
cout << myCar1.brand << " " << myCar1.model << " " << myCar1.year << "\n";
cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year << "\n";
return 0;
}
output :
BMW X5 1999
Ford Mustang 1969
Named Structures
By giving a name to the structure, you can treat it as a data type. This means that you can create variables with this structure anywhere in the program at any time. To create a named structure, put the name of the structure right after the struct keyword:
struct myDataType { // This structure is named "myDataType"
int myNum;
string myString;
};
#include <iostream>
#include <string>
using namespace std;
// Declare a structure named "car"
struct car {
string brand;
string model;
int year;
};
int main() {
// Create a car structure and store it in myCar1;
car myCar1;
myCar1.brand = "BMW";
myCar1.model = "X5";
myCar1.year = 1999;
// Create another car structure and store it in myCar2;
car myCar2;
myCar2.brand = "Ford";
myCar2.model = "Mustang";
myCar2.year = 1969;
// Print the structure members
cout << myCar1.brand << " " << myCar1.model << " " << myCar1.year << "\n";
cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year << "\n";
return 0;
}
output :
BMW X5 1999
Ford Mustang 1969
C++ References
A reference variable is a "reference" to an existing variable, and it is created with the & operator:
string food = "Pizza"; // food variable
string &meal = food; // reference to food
Now, we can use either the variable name food or the reference name meal to refer to the food variable:
#include <iostream>
#include <string>
using namespace std;
int main() {
string food = "Pizza";
string &meal = food;
cout << food << "\n"; // Outputs Pizza
cout << meal << "\n"; // Outputs Pizza
return 0;
}
Memory Address
In the example from the previous page, the & operator was used to create a reference
variable. But it can also be used to get the memory address of a variable; which is the location of
where the variable is stored on the computer.
When a variable is created in C++, a memory address is assigned to the variable. And when we assign a
value to the variable, it is stored in this memory address.
To access it, use the & operator, and the result will represent where the variable is stored:
Note: The memory address is in hexadecimal form (0x..). Note that you may not get the same result in
your program.
#include <iostream>
#include <string>
using namespace std;
int main() {
string food = "Pizza";
cout << &food; // Outputs 0x6dfed4
return 0;
}
C++ Pointers
You learned from the previous chapter, that we can get the memory address of a variable by using the & operator:
#include <iostream>
#include <string>
using namespace std;
int main() {
string food = "Pizza"; // A food variable of type string
cout << food << "\n"; // Outputs the value of food (Pizza)
cout << &food << "\n"; // Outputs the memory address of food (0x6dfed4)
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
string food = "Pizza"; // A string variable
string* ptr = &food; // A pointer variable that stores the address of food
// Output the value of food (Pizza)
cout << food << "\n";
// Output the memory address of food (0x6dfed4)
cout << &food << "\n";
// Output the memory address of food with the pointer (0x6dfed4)
cout << ptr << "\n";
return 0;
}
C++ Dereference
In the example from the previous page, we used the pointer variable to get the memory address of a variable (used together with the & reference operator). However, you can also use the pointer to get the value of the variable, by using the * operator (the dereference operator):
#include <iostream>
#include <string>
using namespace std;
int main() {
string food = "Pizza"; // Variable declaration
string* ptr = &food; // Pointer declaration
// Reference: Output the memory address of food with the pointer (0x6dfed4)
cout << ptr << "\n";
// Dereference: Output the value of food with the pointer (Pizza)
cout << *ptr << "\n";
return 0;
}
C++ Create a Function
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
Functions are used to perform certain actions, and they are important for reusing code: Define the code
once, and use it many times.
C++ provides some pre-defined functions, such as main(), which is used to execute code. But you can also
create your own functions to perform certain actions.
To create (often referred to as declare) a function, specify the name of the function, followed by
parentheses ():
void myFunction() {
// code to be executed
}
Call a Function
Declared functions are not executed immediately. They are "saved for later use", and will be
executed later, when they are called.
To call a function, write the function's name followed by two parentheses () and a semicolon ;
In the following example, myFunction() is used to print a text (the action), when it is called:
#include <iostream>
using namespace std;
// Create a function
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction(); // call the function
return 0;
}
// Outputs "I just got executed!"
#include <iostream>
using namespace std;
void myFunction() {
cout << "I just got executed!\n";
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
// I just got executed!
// I just got executed!
// I just got executed!
Function Declaration and Definition
A C++ function consist of two parts:
Declaration: the return type, the name of the function, and parameters (if any)
Definition: the body of the function (code to be executed)
void myFunction() { // declaration
// the body of the function (definition)
}
#include <iostream>
using namespace std;
// Function declaration
void myFunction();
// The main method
int main() {
myFunction(); // call the function
return 0;
}
// Function definition
void myFunction() {
cout << "I just got executed!";
}
C++ Function Parameters
Information can be passed to functions as a parameter. Parameters act as variables inside
the function.
Parameters are specified after the function name, inside the parentheses. You can add as many parameters
as you want, just separate them with a comma:
void functionName(parameter1, parameter2, parameter3) {
// code to be executed
}
#include <iostream>
#include <string>
using namespace std;
void myFunction(string fname) {
cout << fname << " Refsnes\n";
}
int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
C++ Default Parameters
You can also use a default parameter value, by using the equals sign (=).
If we call the function without an argument, it uses the default value ("Norway"):
#include <iostream>
#include <string>
using namespace std;
void myFunction(string country = "Norway") {
cout << country << "\n";
}
int main() {
myFunction("Sweden");
myFunction("India");
myFunction();
myFunction("USA");
return 0;
}
// Sweden
// India
// Norway
// USA
C++ Multiple Parameters
Inside the function, you can add as many parameters as you want:
#include <iostream>
#include <string>
using namespace std;
void myFunction(string fname, int age) {
cout << fname << " Refsnes. " << age << " years old. \n";
}
int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
// Liam Refsnes. 3 years old.
// Jenny Refsnes. 14 years old.
// Anja Refsnes. 30 years old.
C++ The Return Keyword
The void keyword, used in the previous examples, indicates that the function should not return a value. If you want the function to return a value, you can use a data type (such as int, string, etc.) instead of void, and use the return keyword inside the function:
#include <iostream>
using namespace std;
int myFunction(int x) {
return 5 + x;
}
int main() {
cout << myFunction(3);
return 0;
}
// Outputs 8 (5 + 3)
#include <iostream>
using namespace std;
int myFunction(int x, int y) {
return x + y;
}
int main() {
cout << myFunction(5, 3);
return 0;
}
// Outputs 8 (5 + 3)
#include <iostream>
using namespace std;
int myFunction(int x, int y) {
return x + y;
}
int main() {
int z = myFunction(5, 3);
cout << z;
return 0;
}
// Outputs 8 (5 + 3)
C++ Functions - Pass By Reference
In the examples from the previous page, we used normal variables when we passed parameters to a function. You can also pass a reference to the function. This can be useful when you need to change the value of the arguments:
#include <iostream>
using namespace std;
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "\n";
cout << firstNum << secondNum << "\n";
// Call the function, which will change the values of firstNum and secondNum
swapNums(firstNum, secondNum);
cout << "After swap: " << "\n";
cout << firstNum << secondNum << "\n";
return 0;
}
output :
Before swap:
1020
After swap:
2010
C++ Pass Array to a Function
You can also pass arrays to a function:
#include <iostream>
using namespace std;
void myFunction(int myNumbers[5]) {
for (int i = 0; i < 5; i++) {
cout << myNumbers[i] << "\n";
}
}
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
myFunction(myNumbers);
return 0;
}
output :
10
20
30
40
50
Function Overloading
With function overloading, multiple functions can have the same name with different parameters:
int myFunction(int x)
float myFunction(float x)
double myFunction(double x, double y)
Consider the following example, which have two functions that add numbers of different type:
#include <iostream>
using namespace std;
int plusFuncInt(int x, int y) {
return x + y;
}
double plusFuncDouble(double x, double y) {
return x + y;
}
int main() {
int myNum1 = plusFuncInt(8, 5);
double myNum2 = plusFuncDouble(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
Instead of defining two functions that should do the same thing, it is better to overload one. In the example below, we overload the plusFunc function to work for both int and double:
#include <iostream>
using namespace std;
int plusFunc(int x, int y) {
return x + y;
}
double plusFunc(double x, double y) {
return x + y;
}
int main() {
int myNum1 = plusFunc(8, 5);
double myNum2 = plusFunc(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
output :
Int: 13
Double: 10.56
C++ Recursion
Recursion is the technique of making a function call itself. This technique provides a way
to break complicated problems down into simple problems which are easier to solve.
Recursion may be a bit difficult to understand. The best way to figure out how it works is to experiment
with it.
#include <iostream>
using namespace std;
int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
int main() {
int result = sum(10);
cout << result;
return 0;
}
output : 55
Example Explained
When the sum() function is called, it adds parameter k to the sum of all numbers smaller than k and returns the result. When k becomes 0, the function just returns 0. When running, the program follows these steps: 10 + sum(9)
10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
Since the function does not call itself when k is 0, the program stops there and returns the result.
C++ OOP
OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or functions that perform operations on the data,
while object-oriented programming is about creating objects that contain both data and functions.
C++ Classes and Objects
C++ is an object-oriented programming language.
Everything in C++ is associated with classes and objects, along with its attributes and methods. For
example: in real life, a car is an object. The car has attributes, such as weight and color, and
methods, such as drive and brake.
Attributes and methods are basically variables and functions that belongs to the class. These are often
referred to as "class members".
A class is a user-defined data type that we can use in our program, and it works as an object
constructor, or a "blueprint" for creating objects
Create a Class
To create a class, use the class keyword:
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
Create an Object
In C++, an object is created from a class. We have already created the class named MyClass,
so now we can use this to create objects.
To create an object of MyClass, specify the class name, followed by the object name.
To access the class attributes (myNum and myString), use the dot syntax (.) on the object:
#include <iostream>
#include <string>
using namespace std;
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
int main() {
MyClass myObj; // Create an object of MyClass
// Access attributes and set values
myObj.myNum = 15;
myObj.myString = "Some text";
// Print values
cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}
output :
15
Some text
Multiple Objects
You can create multiple objects of one class:
#include <iostream>
#include <string>
using namespace std;
class Car {
public:
string brand;
string model;
int year;
};
int main() {
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;
Car carObj2;
carObj2.brand = "Ford";
carObj2.model = "Mustang";
carObj2.year = 1969;
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
output :
BMW X5 1999
Ford Mustang 1969
C++ Class Methods
Methods are functions that belongs to the class.
There are two ways to define functions that belongs to a class:
Inside class definition
Outside class definition
In the following example, we define a function inside the class, and we name it "myMethod".
Note: You access methods just like you access attributes; by creating an object of the class and using
the dot syntax (.):
Inside Example
#include <iostream>
using namespace std;
class MyClass { // The class
public: // Access specifier
void myMethod() { // Method/function
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
output : Hello World!
Outside Example
#include <iostream>
using namespace std;
class MyClass { // The class
public: // Access specifier
void myMethod(); // Method/function declaration
};
// Method/function definition outside the class
void MyClass::myMethod() {
cout << "Hello World!";
}
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
output : Hello World!
Parameters
You can also add parameters:
#include <iostream>
using namespace std;
class Car {
public:
int speed(int maxSpeed);
};
int Car::speed(int maxSpeed) {
return maxSpeed;
}
int main() {
Car myObj;
cout << myObj.speed(200);
return 0;
}
output : 200
C++ Constructors
A constructor in C++ is a special method that is automatically called when an object of a
class is created.
To create a constructor, use the same name as the class, followed by parentheses ():
#include <iostream>
using namespace std;
class MyClass { // The class
public: // Access specifier
MyClass() { // Constructor
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass (this will call the constructor)
return 0;
}
output : Hello World!
Constructor Parameters
Constructors can also take parameters (just like regular functions), which can be useful for
setting initial values for attributes.
The following class have brand, model and year attributes, and a constructor with different parameters.
Inside the constructor we set the attributes equal to the constructor parameters (brand=x, etc). When we
call the constructor (by creating an object of the class), we pass parameters to the constructor, which
will set the value of the corresponding attributes to the same:
#include <iostream>
using namespace std;
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z) { // Constructor with parameters
brand = x;
model = y;
year = z;
}
};
int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
output :
BMW X5 1999
Ford Mustang 1969
#include <iostream>
using namespace std;
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z); // Constructor declaration
};
// Constructor definition outside the class
Car::Car(string x, string y, int z) {
brand = x;
model = y;
year = z;
}
int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
output :
BMW X5 1999
Ford Mustang 1969
C++ Access Specifiers
By now, you are quite familiar with the public keyword that appears in all of our class examples:
#include <iostream>
using namespace std;
class MyClass { // The class
public: // Public access specifier
int x; // Public attribute (int variable)
};
int main() {
MyClass myObj; // Create an object of MyClass
// Access attributes and set values
myObj.x = 15;
// Print values
cout << myObj.x;
return 0;
}
output : 15
In C++, there are three access specifiers:
public - members are accessible from outside the class
private - members cannot be accessed (or viewed) from outside the class
protected - members cannot be accessed from outside the class, however, they can be accessed in
inherited classes. You will learn more about Inheritance later.
In the following example, we demonstrate the differences between public and private members:
#include <iostream>
using namespace std;
class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};
int main() {
MyClass myObj;
myObj.x = 25; // Allowed (x is public)
myObj.y = 50; // Not allowed (y is private)
return 0;
}
output : In function 'int main()':
Line 8: error: 'int MyClass::y' is private
Line 14: error: within this context
Note: By default, all members of a class are private if you don't specify an access specifier:
class MyClass {
int x; // Private attribute
int y; // Private attribute
};
C++ Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must declare class variables/attributes as private (cannot be accessed from outside the class). If you want others to read or modify the value of a private member, you can provide public get and set methods.
Access Private Members
To access a private attribute, use public "get" and "set" methods:
#include <iostream>
using namespace std;
class Employee {
private:
int salary;
public:
void setSalary(int s) {
salary = s;
}
int getSalary() {
return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
}
output : 50000
Example explained
The salary attribute is private, which have restricted access.
The public setSalary() method takes a parameter (s) and assigns it to the salary attribute (salary = s).
The public getSalary() method returns the value of the private salary attribute.
Inside main(), we create an object of the Employee class. Now we can use the setSalary() method to set
the value of the private attribute to 50000. Then we call the getSalary() method on the object to return
the value.
C++ Inheritance
In C++, it is possible to inherit attributes and methods from one class to another. We group
the "inheritance concept" into two categories:
derived class (child) - the class that inherits from another class
base class (parent) - the class being inherited from
To inherit from a class, use the : symbol.
In the example below, the Car class (child) inherits the attributes and methods from the Vehicle class
(parent):
#include <iostream>
#include <string>
using namespace std;
// Base class
class Vehicle {
public:
string brand = "Ford";
void honk() {
cout << "Tuut, tuut! \n" ;
}
};
// Derived class
class Car: public Vehicle {
public:
string model = "Mustang";
};
int main() {
Car myCar;
myCar.honk();
cout << myCar.brand + " " + myCar.model;
return 0;
}
output :
Tuut, tuut!
Ford Mustang
C++ Multilevel Inheritance
A class can also be derived from one class, which is already derived from another class. In the following example, MyGrandChild is derived from class MyChild (which is derived from MyClass).
#include <iostream>
using namespace std;
// Parent class
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};
// Child class
class MyChild: public MyClass {
};
// Grandchild class
class MyGrandChild: public MyChild {
};
int main() {
MyGrandChild myObj;
myObj.myFunction();
return 0;
}
Output :
Some content in parent class.
C++ Multiple Inheritance
A class can also be derived from more than one base class, using a comma-separated list:
#include <iostream>
using namespace std;
// Base class
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class.\n" ;
}
};
// Another base class
class MyOtherClass {
public:
void myOtherFunction() {
cout << "Some content in another class.\n" ;
}
};
// Derived class
class MyChildClass: public MyClass, public MyOtherClass {
};
int main() {
MyChildClass myObj;
myObj.myFunction();
myObj.myOtherFunction();
return 0;
}
output :
Some content in parent class.
Some content in another class.
C++ Inheritance Access
You learned from the Access Specifiers chapter that there are three specifiers available in C++. Until now, we have only used public (members of a class are accessible from outside the class) and private (members can only be accessed within the class). The third specifier, protected, is similar to private, but it can also be accessed in the inherited class:
#include <iostream>
using namespace std;
// Base class
class Employee {
protected: // Protected access specifier
int salary;
};
// Derived class
class Programmer: public Employee {
public:
int bonus;
void setSalary(int s) {
salary = s;
}
int getSalary() {
return salary;
}
};
int main() {
Programmer myObj;
myObj.setSalary(50000);
myObj.bonus = 15000;
cout << "Salary: " << myObj.getSalary() << "\n";
cout << "Bonus: " << myObj.bonus << "\n";
return 0;
}
output :
Salary: 50000
Bonus: 15000
C++ Files
The fstream library allows us to work with files.
To use the fstream library, include both the standard <iostream> AND the <fstream> header
file:
#include <iostream>
#include <fstream>
There are three classes included in the fstream library, which are used to create, write or
read files:
ofstream : Creates and writes to files
ifstream : Reads from files
fstream : A combination of ofstream and ifstream: creates, reads, and writes to files
Create and Write To a File
To create a file, use either the ofstream or fstream class, and specify the name of the
file.
To write to the file, use the insertion operator (<<).< /p>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create and open a text file
ofstream MyFile("filename.txt");
// Write to the file
MyFile << "Files can be tricky, but it is fun enough!";
// Close the file
MyFile.close();
}
Read a File
To read from a file, use either the ifstream or fstream class, and the name of the
file.
Note that we also use a while loop together with the getline() function (which belongs to the
ifstream class) to read the file line by line, and to print the content of the file:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
// Create a text file
ofstream MyWriteFile("filename.txt");
// Write to the file
MyWriteFile << "Files can be tricky, but it is fun enough!";
// Close the file
MyWriteFile.close();
// Create a text string, which is used to output the text file
string myText;
// Read from the text file
ifstream MyReadFile("filename.txt");
// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText)) {
// Output the text from the file
cout << myText;
}
// Close the file
MyReadFile.close();
}
output :
Files can be tricky, but it is fun enough!
C++ Exceptions
When executing C++ code, different errors can occur: coding errors made by the programmer,
errors due to wrong input, or other unforeseeable things.
When an error occurs, C++ will normally stop and generate an error message. The technical term for this
is: C++ will throw an exception (throw an error).
C++ try and catch
Exception handling in C++ consist of three keywords: try, throw and catch:
The try statement allows you to define a block of code to be tested for errors while it is being
executed.
The throw keyword throws an exception when a problem is detected, which lets us create a custom error.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try
block.
The try and catch keywords come in pairs:
try {
// Block of code to try
throw exception; // Throw an exception when a problem arise
}
catch () {
// Block of code to handle errors
}
#include <iostream>
using namespace std;
int main() {
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - you are old enough.";
} else {
throw (age);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Age is: " << myNum;
}
return 0;
}
output :
Access denied - You must be at least 18 years old.
Age is: 15
Handle Any Type of Exceptions (...)
If you do not know the throw type used in the try block, you can use the "three dots" syntax (...) inside the catch block, which will handle any type of exception:
#include <iostream>
using namespace std;
int main() {
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - you are old enough.";
} else {
throw 505;
}
}
catch (...) {
cout << "Access denied - You must be at least 18 years old.\n";
}
return 0;
}
output : Access denied - You must be at least 18 years old.